<script setup lang="ts">
import {reactive, ref} from 'vue';
import {Search, Refresh, Plus} from '@element-plus/icons-vue';
import {addPlatDataInter, getPlatuserInter, resetPwdInter} from "@/api/interface/interFace";
import {addPlatFn, changePlat, getPlatuser, resetPwd} from "@/api/system/plat-user";
import request from "@/utils/request";
import {ElMessage, UploadProps} from "element-plus";
import {getToken} from "@/utils/auth";
import router from "@/router";
const platUserData = ref<getPlatuserInter>({
    nickName: '',
    company: '',
    pageNum: 1,
    pageSize: 10
});
const rules = ref({
    nickName: [{
        required: true,
        message: '请输入姓名',
        trigger: 'blur'
    }],
    username: [{
        required: true,
        message: '请输入用户名',
        trigger: 'blur'
    }],
    avatar: [{
        required: true,
        message: '请上传头像',
        trigger: 'blur'
    }],
    company: [{
        required: true,
        message: '请输入公司名称',
        trigger: 'blur'
    }],
    phone: [{
        required: true,
        message: '请输入手机号',
        trigger: 'blur'
    }],
    companyIntroRich: [{
        required: true,
        message: '请输入公司介绍',
        trigger: 'blur'
    }],
});
const rules2 = ref({
    nickName: [{
        required: true,
        message: '请输入姓名',
        trigger: 'blur'
    }],
    username: [{
        required: true,
        message: '请输入用户名',
        trigger: 'blur'
    }],
    avatar: [{
        required: true,
        message: '请上传头像',
        trigger: 'blur'
    }],
    company: [{
        required: true,
        message: '请输入公司名称',
        trigger: 'blur'
    }],
    phone: [{
        required: true,
        message: '请输入手机号',
        trigger: 'blur'
    }],
    password: [{
        required: true,
        message: '请输入密码',
        trigger: 'blur'
    }],
    companyIntroRich: [{
        required: true,
        message: '请输入公司介绍',
        trigger: 'blur'
    }],
});
let platUserInfo = ref<object[]>([]);
let appInfototal = ref(0);
getPlatuser(platUserData.value).then(res => {
    platUserInfo.value?.push((res as any).rows);
    appInfototal.value = (res as any).total;
    (platUserInfo as any).value[0].forEach(item => {
        if (item.loginAllow === 1) {
            item.loginText = '禁止登录';
        } else {
            item.loginText = '允许登录';
        }
    });
});

const handleCurrentChange = (val: number) => {
    platUserData.value.pageNum = val;
    platUserInfo.value.length = 0;
    getPlatuser(platUserData.value).then(res => {
        platUserInfo.value?.push((res as any).rows);
        (platUserInfo as any).value[0].forEach(item => {
            if (item.loginAllow === 1) {
                item.loginText = '禁止登录';
            } else {
                item.loginText = '允许登录';
            }
        });
    });
};

function searchPlatuser() {
    platUserInfo.value.length = 0;
    getPlatuser(platUserData.value).then(res => {
        platUserInfo.value?.push((res as any).rows);
        appInfototal.value = (res as any).total;
        (platUserInfo as any).value[0].forEach(item => {
            if (item.loginAllow === 1) {
                item.loginText = '禁止登录';
            } else {
                item.loginText = '允许登录';
            }
        });
    });
}

function reset() {
    platUserData.value.nickName = '';
    platUserData.value.company = '';
    platUserInfo.value.length = 0;
    getPlatuser(platUserData.value).then(res => {
        platUserInfo.value?.push((res as any).rows);
        appInfototal.value = (res as any).total;
        (platUserInfo as any).value[0].forEach(item => {
            if (item.loginAllow === 1) {
                item.loginText = '禁止登录';
            } else {
                item.loginText = '允许登录';
            }
        });
    });
}

//查询单条数据
function getOncePlatuser(userId) {
    return request({
        url: `/jsUser/${userId}`,
        method: 'get',
    });
}

let changeFormVisible = ref(false);
let changeInfoUrl = ref('');

function changePlatuser(id) {
    getOncePlatuser(id).then(res => {
        changePlatData.value.userId = id;
        changePlatData.value.nickName = res.data.nickName;
        changePlatData.value.avatar = res.data.avatar;
        changePlatData.value.company = res.data.company;
        changePlatData.value.phone = res.data.phone;
        changePlatData.value.companyIntroRich = res.data.companyIntroRich;
        changePlatData.value.username = res.data.username;
        changeInfoUrl.value = '/dev-api' + res.data.avatar;

    });
    changeFormVisible.value = true;

}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    changeInfoUrl.value = URL.createObjectURL(uploadFile.raw!);
    changePlatData.value.avatar = (uploadFile as any).response.fileName;
};

const handleAvatarSuccessAdd: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    addimgUrl.value = URL.createObjectURL(uploadFile.raw!);
    addPlatData.value.avatar = (uploadFile as any).response.fileName;
};
const changePlatData = ref({
    userId: 0,
    username: '',
    avatar: '',
    company: '',
    phone: '',
    companyIntroRich: '',
    nickName: ''
});
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图片必须是jpg/jpeg格式');
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!');
        return false;
    }
    return true;
};
const addGiftImg = reactive({'Authorization': 'Bearer ' + getToken()});
const elRef = ref(null);

function changePlatForm() {
    (elRef as any).value.validate((valid) => {
        if (valid) {
            changePlat(changePlatData.value).then(() => {
                ElMessage.success('修改成功');
                platUserInfo.value.length = 0;
                getPlatuser(platUserData.value).then(res => {
                    platUserInfo.value?.push((res as any).rows);
                    (platUserInfo as any).value[0].forEach(item => {
                        if (item.loginAllow === 1) {
                            item.loginText = '禁止登录';
                        } else {
                            item.loginText = '允许登录';
                        }
                    });
                });
                changeFormVisible.value = false;
            });

        } else {
            ElMessage.error('提交失败');
            return false;
        }
    });
};

function changeCenel() {
    changeFormVisible.value = false;
    addFormVisible.value=false;
    ElMessage('取消操作');
    addPlatData.value.avatar='';
    addPlatData.value.username='';
    addPlatData.value.company='';
    addPlatData.value.password='';
    addPlatData.value.phone='';
    addPlatData.value.companyIntroRich='';
    addPlatData.value.nickName='';
}

//新增用户
let addFormVisible = ref(false);
let addPlatData=ref<addPlatDataInter>({
    username:'',
    avatar:'',
    company:'',
    phone:'',
    password:'',
    nickName:'',
    companyIntroRich:'',
});
let addimgUrl=ref('');
function addPlat() {
    addFormVisible.value = true;
}
const addRef = ref(null);
function addPlatForm() {
    (addRef as any).value.validate((valid) => {
        if (valid) {
            addPlatFn(addPlatData.value).then(() => {
                ElMessage.success('添加新用户成功');
                platUserInfo.value.length = 0;
                getPlatuser(platUserData.value).then(res => {
                    platUserInfo.value?.push((res as any).rows);
                    (platUserInfo as any).value[0].forEach(item => {
                        if (item.loginAllow === 1) {
                            item.loginText = '禁止登录';
                        } else {
                            item.loginText = '允许登录';
                        }
                    });
                });
            });
            addPlatData.value.avatar='';
            addPlatData.value.username='';
            addPlatData.value.company='';
            addPlatData.value.password='';
            addPlatData.value.phone='';
            addPlatData.value.companyIntroRich='';
            addPlatData.value.nickName='';
            addFormVisible.value = false;
        } else {
            ElMessage.error('提交失败');
            return false;
        }
    });
}

//删除用户==========================================================================
const deletePlatDog = ref(false);
const PlatId = ref();

function deletePlatFn(userIdList) {
    return request({
        url: '/jsUser?userIdList=' + userIdList,
        method: 'delete',
    });
}

function deletePlat(id) {
    PlatId.value = id;
    deletePlatDog.value = true;
}

function cencelDelete() {
    deletePlatDog.value = false;
    changePwdDog.value = false;
    ElMessage('取消操作');
    password.value='';
    surepwd.value='';
}

function sureDelete() {
    deletePlatFn(PlatId.value).then(() => {
        ElMessage.success('删除成功');
        deletePlatDog.value = false;
        platUserInfo.value.length = 0;
        getPlatuser(platUserData.value).then(res => {
            platUserInfo.value?.push((res as any).rows);
        });
    });

}

//禁止登陆============================================================================

const changeStatus = ref({
    userId: 0,
    loginAllow: 0
});

function loginStatus(id, index) {
    getOncePlatuser(id).then(res => {
        if (res.data.loginAllow === 1) {
            changeStatus.value.loginAllow = 0;
        } else {
            changeStatus.value.loginAllow = 1;
        }
        changeStatus.value.userId = id;
        changePlat(changeStatus.value).then(() => {
            ElMessage.success('修改成功');
        });
        platUserInfo.value.length = 0;
        getPlatuser(platUserData.value).then(res => {
            platUserInfo.value?.push((res as any).rows);
            (platUserInfo as any).value[0].forEach(item => {
                if (item.loginAllow === 1) {
                    item.loginText = '禁止登录';
                } else {
                    item.loginText = '允许登录';
                }
            });
        });
    });

}

//重置密码==================================================================
const resetData = ref<resetPwdInter>({
    userId: 0,
    password: ''
});
const changePwdDog = ref(false);

function resetPwdBtn(id) {
    changePwdDog.value = true;
    resetData.value.userId = id;
}

const password = ref();
const surepwd = ref();

function surechangePwd() {
    if (password.value === surepwd.value) {
        resetData.value.password = password.value;
        resetPwd(resetData.value).then((res) => {
            ElMessage.success('修改成功');
            changePwdDog.value = false;
        });
    } else {
        ElMessage.error('两次密码不一致！');
    }
}
function jumpUserEquity(id){
    router.push({path: '/system/UserEquity', query: {userId: id}});
}
</script>
<template>
    <div>
        <div class="title" style="position: relative">
            <span class="inputTitle">姓名</span>
            <el-input
                v-model="platUserData.nickName"
                class="activeName"
                placeholder="请输入姓名"
                clearable
                size="large"
            />
            <span class="inputTitle">公司名称</span>
            <el-input
                v-model="platUserData.company"
                class="activeName"
                placeholder="请输入公司名称"
                clearable
                size="large"
            />
            <span class="btns">
            <el-button type="primary" :icon="Search" class="serachBtn" @click="searchPlatuser">查询</el-button>
            <el-button :icon="Refresh" class="refreshBtn" @click="reset">重置</el-button>
        </span>
        </div>
        <section class='tableBox' style="padding: 0 30px">
            <el-button type="primary" :icon="Plus" style="margin-top: 20px;" @click="addPlat">新增</el-button>
            <el-table :data="(platUserInfo[0] as any)" style="width: 100%;margin-top: 20px" stripe>
                <template #empty>
                    <el-empty description="暂无数据"/>
                </template>
                <el-table-column prop="nickName" label="姓名" height width="280"/>
                <el-table-column prop="company" label="公司" height width="280"/>
                <el-table-column prop="phone" label="手机号" height width="280"/>
                >
                <el-table-column prop="操作" label="操作" height>
                    <template #default="index">
                        <button style="color: #1c84c6;margin-left: 20px" @click="changePlatuser(index.row.userId)">编辑</button>
                        <button style="color: #1c84c6;margin-left: 20px" @click="deletePlat(index.row.userId)">删除</button>
                        <button style="color: #1c84c6;margin-left: 20px" @click="loginStatus(index.row.userId,index.$index)"
                                v-text="index.row.loginText"></button>
                        <button style="color: #1c84c6;margin-left: 20px" @click="resetPwdBtn(index.row.userId)">重置密码</button>
                        <button style="color: #1c84c6;margin-left: 20px" @click="jumpUserEquity(index.row.userId)">会员权益</button>
                    </template>
                </el-table-column>
            </el-table>
        </section>
        <div style="position: relative">
            <span style="margin-left: 1000px;position: absolute;top: 8px">共{{ appInfototal }}条数据</span>
            <el-pagination
                style="margin-top: 20px;margin-left: 1150px"
                :page-size="platUserData.pageSize"
                layout="prev, pager, next"
                :total="appInfototal"
                @currentChange="handleCurrentChange"
            />
        </div>
        <el-dialog v-model="deletePlatDog" title="提示" width="500" center>
            <el-icon color="rgb(255, 186, 0)" size="25">
                <Warning/>
            </el-icon>
            <span style="font-size: 20px;vertical-align: top;margin-left: 10px">进行删除操作后无法恢复，是否继续删除？</span>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cencelDelete">取消</el-button>
                    <el-button type="primary" @click="sureDelete">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="changePwdDog" title="修改密码" width="500" center>
            <el-form-item>
                <el-input
                    v-model="password"
                    placeholder="请输入新密码"
                    type="password"
                    show-password
                    clearable
                    size="large"></el-input>
            </el-form-item>
            <el-form-item>
                <el-input
                    v-model="surepwd"
                    placeholder="请确认密码"
                    type="password"
                    show-password
                    clearable
                    size="large"></el-input>
            </el-form-item>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="surechangePwd">
                        确定
                    </el-button>
                    <el-button @click="cencelDelete">取消</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="changeFormVisible" title="编辑" width="900" style="padding: 20px">
            <el-form ref="elRef" :model="changePlatData" :rules="rules">
                <el-form-item label="姓名：" prop="nickName">
                    <el-input
                        v-model="changePlatData.nickName"
                        placeholder="请输入姓名"
                        clearable
                        size="large"></el-input>
                </el-form-item>
                <el-form-item label="用户名：" prop="username">
                    <el-input
                        v-model="changePlatData.username"
                        placeholder="请输入用户名"
                        clearable
                        size="large"></el-input>
                </el-form-item>
                <el-form-item label="头像：" prop="avatar">
                    <el-upload
                        class="avatar-uploader"
                        action="/dev-api/common/upload"
                        :show-file-list="false"
                        :on-success="(handleAvatarSuccess as any)"
                        :before-upload="beforeAvatarUpload"
                        :headers="addGiftImg"
                    >
                        <img v-if="changeInfoUrl" :src="changeInfoUrl" class="avatar" style="width: 150px;height: 150px"/>
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus/>
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="公司名称：" prop="company">
                    <el-input
                        v-model="changePlatData.company"
                        placeholder="请输入公司名称"
                        clearable
                        size="large"></el-input>
                </el-form-item>
                <el-form-item label="手机号：" prop="phone">
                    <el-input
                        v-model="changePlatData.phone"
                        placeholder="请输入手机号"
                        clearable
                        size="large"></el-input>
                </el-form-item>
                <el-form-item label="公司介绍：" prop="companyIntroRich">
                    <editor
                        v-model="changePlatData.companyIntroRich"
                        placeholder="请输入公司介绍"
                        clearable
                        size="large"></editor>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer" style="margin-left: 360px">
                    <el-form-item>
                        <el-button size="large" @click="changeCenel">取消</el-button>
                        <el-button type="primary" size="large" @click="changePlatForm">确定</el-button>
                    </el-form-item>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="addFormVisible" title="新增" width="900" style="padding: 20px">
            <el-form ref="addRef" :model="addPlatData" :rules="rules2">
                <el-form-item label="姓名：" prop="nickName">
                    <el-input
                        v-model="addPlatData.nickName"
                        placeholder="请输入姓名"
                        clearable
                        size="large"></el-input>
                </el-form-item>
                <el-form-item label="用户名：" prop="username">
                    <el-input
                        v-model="addPlatData.username"
                        placeholder="请输入用户名"
                        clearable
                        size="large"></el-input>
                </el-form-item>
                <el-form-item label="头像：" prop="avatar">
                    <el-upload
                        class="avatar-uploader"
                        action="/dev-api/common/upload"
                        :show-file-list="false"
                        :on-success="(handleAvatarSuccessAdd as any)"
                        :before-upload="beforeAvatarUpload"
                        :headers="addGiftImg"
                    >
                        <img v-if="addimgUrl" :src="addimgUrl" class="avatar" style="width: 150px;height: 150px"/>
                        <el-icon v-else class="avatar-uploader-icon"  style="width: 150px;height: 150px">
                            <Plus/>
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="公司名称：" prop="company">
                    <el-input
                        v-model="addPlatData.company"
                        placeholder="请输入公司名称"
                        clearable
                        size="large"></el-input>
                </el-form-item>
                <el-form-item label="手机号：" prop="phone">
                    <el-input
                        v-model="addPlatData.phone"
                        placeholder="请输入手机号"
                        clearable
                        size="large"></el-input>
                </el-form-item>
                <el-form-item label="密码：" prop="password">
                    <el-input
                        v-model="addPlatData.password"
                        placeholder="请输入密码"
                        clearable
                        type="password"
                        show-password
                        size="large"></el-input>
                </el-form-item>
                <el-form-item label="公司介绍：" prop="companyIntroRich">
                    <editor
                        v-model="addPlatData.companyIntroRich"
                        placeholder="请输入公司介绍"
                        clearable
                        size="large"></editor>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer" style="margin-left: 360px">
                    <el-form-item>
                        <el-button size="large" @click="changeCenel">取消</el-button>
                        <el-button type="primary" size="large" @click="addPlatForm">确定</el-button>
                    </el-form-item>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
.addInfo {
    margin-top: 15vh !important;
    width: 40%;
    padding: 20px;
}

.addactiveName {
    width: 60%;
}

.btnClass {
    color: rgb(204, 196, 207) !important;
    cursor: no-drop;
}

.el-table .el-table__cell {
    padding: 18px !important;
}

.dialog {
    padding: 30px;
}


.el-header {
    background-color: rgb(248, 248, 249);
    height: 44px;
    font-size: 14px;
    font-weight: 600;
    color: #444;
    padding: 0 70px;
    line-height: 44px;
    border-bottom: 1px solid #d9d9d9;
}

.ulTitle {
    display: flex;
    justify-content: space-between;
}

li {
    list-style: none;
    float: left;
}

.btns {
    margin-left: 80px;
    position: absolute;
    bottom: -10px;
}

.serachBtn, .refreshBtn {
    width: 73px !important;
    height: 28px !important;
}

.demo-date-picker {
    display: flex;
    width: 100%;
    padding: 0;
    flex-wrap: wrap;
}

.demo-date-picker .block {
    padding: 30px 0;
    text-align: center;
    border-right: solid 1px var(--el-border-color);
    flex: 1;
}

.demo-date-picker .block:last-child {
    border-right: none;
}

.demo-date-picker .demonstration {
    display: block;
    color: var(--el-text-color-secondary);
    font-size: 14px;
    margin-bottom: 20px;
}

.title {
    height: 65px;
    border-bottom: 1px solid rgb(237, 237, 237);
    line-height: 65px;
    padding: 0 45px;
    overflow: hidden;
}

.inputTitle {
    font-size: 14px;
    font-weight: bolder;
    color: #666;

}

.activeName {
    width: 15%;
    margin-left: 15px;
    margin-right: 15px;
    height: 28px;
    font-size: 12px;
}

.el-date-editor .el-range-input {
    font-size: 12px;
}

.el-select-dropdown__item {
    width: 100% !important;
}


/deep/ .el-form-item__label {
    width: 15%;
    font-weight: 700 !important;
    font-size: 18px;
}

/deep/ .cell {
    text-align: center;
    font-size: 16px;
}
</style>
